package com.wuuxiang.i5xforyou.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuuxiang.i5xforyou.common.consts.Consts;
import com.wuuxiang.i5xforyou.common.domain.ResultMsg;
import com.wuuxiang.i5xforyou.common.domain.Results;
import com.wuuxiang.i5xforyou.common.redis.RedisKey;
import com.wuuxiang.i5xforyou.common.service.impl.BaseServiceImpl;
import com.wuuxiang.i5xforyou.service.CommonService;
import com.wuuxiang.i5xforyou.utils.HttpUtil;
import com.wuuxiang.i5xforyou.vo.CrmVersion;
import com.wuuxiang.i5xforyou.vo.ShopInfo;
import com.wuuxiang.jdbc.spring.boot.autoconfigure.dao.O2OJdbcRepository;

/** 
 * @ClassName: CommonServiceImpl <br/>
 * crm共同接口service <br/>
 * @author Mobile Web Group-lff
 * @date 2018年3月14日 下午5:22:40
 *
 */
@Service("commonService")
public class CommonServiceImpl extends BaseServiceImpl implements CommonService {

	@Autowired
	private O2OJdbcRepository<String> o2oStringRepository;
	
	@Autowired
	private O2OJdbcRepository<ShopInfo> o2oShopInfoRepository;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	/**
	 * Description: 获取crm版本
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月14日 下午5:31:42
	 * 
	 * @see com.wuuxiang.i5xforyou.service.CommonService#getCrmVersion(java.lang.String)
	 */
	@Override
	public CrmVersion getCrmVersion(String mpId) {
		//先取redis里面的缓存
		String redisKey = RedisKey.CRM_VERSION + "." + mpId;
		String crmVersion = stringRedisTemplate.opsForValue().get(redisKey);
		if (StringUtils.isBlank(crmVersion)) {
			//取db值，先取微信的关系
			StringBuilder wxSql = new StringBuilder();
			wxSql.append(" SELECT PG.CRM_VERSION FROM WX_GROUPCORP WG ");
			wxSql.append(" INNER JOIN PHO_GROUPCORP PG ON WG.GCID = PG.GCID ");
			wxSql.append(" WHERE WG.WX_MP_ID = ? ");
			wxSql.trimToSize();
				
			crmVersion = o2oStringRepository.getJavaBean(wxSql.toString(), String.class, mpId);
			if (StringUtils.isBlank(crmVersion)) {
				//微信关系没取到，再取支付宝
				StringBuilder zfbSql = new StringBuilder();
				zfbSql.append(" SELECT * FROM ( ");
				zfbSql.append(" SELECT PG.CRM_VERSION FROM PHO_ALIPAY_PAY_INFO PAPI ");
				zfbSql.append(" INNER JOIN PHO_MC PM ON PAPI.MCID = PM.MCID ");
				zfbSql.append(" INNER JOIN PHO_GROUPCORP PG ON PM.GCID = PG.GCID ");
				zfbSql.append(" WHERE PAPI.TB_APPID = ? ORDER BY PAPI.CREATETIME DESC ");
				zfbSql.append(" ) WHERE ROWNUM = 1 ");
				zfbSql.trimToSize();
				
				crmVersion = o2oStringRepository.getJavaBean(zfbSql.toString(), String.class, mpId);
			}
			
			if (StringUtils.isNotBlank(crmVersion)) {
				//放入redis,30分钟有效期
				stringRedisTemplate.opsForValue().set(redisKey, crmVersion, 1800, TimeUnit.SECONDS);
			}
		}
		
		if ("7".equals(crmVersion)) {
			return CrmVersion.CRM7;
		} else if ("6".equals(crmVersion)) {
			return CrmVersion.CRM6;
		} else {
			log.error("获取crm版本失败，入参mpId=" + mpId);
			return CrmVersion.UNKNOWN;
		}
	}

	/**
	 * Description: 获取crm7流水号
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月14日 下午5:35:37
	 * 
	 * @see com.wuuxiang.i5xforyou.service.CommonService#getCrm7Code(java.lang.String, java.lang.String)
	 */
	@Override
	public ResultMsg getCrm7Code(String mpId, String openId) {
		ResultMsg resultMsg = new ResultMsg();
		//url
		String url = "";
		//入参
		JSONObject params = new JSONObject();
		params.put("mpId", mpId);
		params.put("openId", openId);
		//出参
		JSONObject resultJson = new JSONObject();
		try {
			//入参
			JSONObject data = new JSONObject();
			data.put("num", 1);
			params.put("data", data);
			//url
			url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/trade/gettscode";
			//调用接口
			resultJson = HttpUtil.doPostCrm7JSONObject(url, params);
			if (resultJson.getIntValue("code") != 200) {
				//失败
				log.error("获取crm7的流水号接口调用失败，url=" + url + ",入参params=" + params+ ",出参result=" + resultJson);
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception(resultJson.getString("msg")));
				return resultMsg;
			}
			JSONArray contentArr = resultJson.getJSONArray("content");
			if (contentArr == null || contentArr.isEmpty()) {
				String msg = "获取crm7的流水号接口没有返回流水号：url=" + url + ",参数params=" + params + "，出参result=" + resultJson;
				log.error(msg);
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception(msg));
				return resultMsg;
			}
			
			//成功
			resultMsg.setState(Results.SUCCESS);
			resultMsg.setMsgEntity(contentArr.getString(0));
			return resultMsg;
		} catch (Exception e) {
			log.error("获取砍价活动券列表失败，url=" + url + ",原因=" + e.toString() + ",入参params=" + params+ ",出参result=" + resultJson);
			resultMsg.setState(Results.ERROR);
			resultMsg.setException(e);
			return resultMsg;
		}
	}

	/**
	 * Description: 获取门店信息的列表
	 * @author: Mobile Web Group-lff
	 * @date: 2018年3月19日 下午4:24:07
	 * 
	 * @see com.wuuxiang.i5xforyou.service.CommonService#getShopInfos(java.lang.String)
	 */
	@Override
	public List<ShopInfo> getShops(String mpId) {
		StringBuilder sql = new StringBuilder();
		//支付宝
		sql.append(" SELECT PM.MCID AS MCID, PM.NAME AS NAME, PM.ADDRESS AS ADDRESS, PM.ORDERTEL AS ORDERTEL FROM PHO_ALIPAY_PAY_INFO PAPI,PHO_MC PM ");
		sql.append(" WHERE PAPI.TB_APPID = ? AND PAPI.MCID = PM.MCID ");
		sql.append(" UNION ");
		//微信
		sql.append(" SELECT PM.MCID AS MCID, PM.NAME AS NAME, PM.ADDRESS AS ADDRESS, PM.ORDERTEL AS ORDERTEL FROM WX_GROUPCORP WG,PHO_MC PM ");
		sql.append(" WHERE WG.WX_MP_ID = ? AND WG.GCID = PM.GCID ");
		
		return o2oShopInfoRepository.getList(sql.toString(), ShopInfo.class, mpId, mpId);
	}

	@Override
	public String getGcIdByMpId(String mpId) {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT PM.GCID FROM PHO_MC PM LEFT JOIN WX_MC_RELATION WMR ON WMR.MCID = PM.MCID WHERE WMR.WX_MP_ID= ? AND ROWNUM = 1");
		return o2oStringRepository.getJavaBean(sql.toString(), String.class, mpId);
	}
	
	
}
